package com.tuo51.manager.service.impl;

import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.query.base.PagerQuery;
import com.tuo51.manager.domain.SysUser;
import com.tuo51.manager.repository.SysUserRepository;
import com.tuo51.manager.service.SysUserService;
import com.tuo51.manager.vo.SysUserVO;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public boolean delete(String id) {

        SysUser user = sysUserRepository.getOne(id);
        if (user == null){

        }
        user.setDeleted(true);

        sysUserRepository.save(user);

        return user.getDeleted();
    }

    @Override
    public SysUser get(String sysUserId){
        return sysUserRepository.getOne(sysUserId);
    }

    @Override
    public Page<SysUserVO> page(PagerQuery pagerQuery) {

        //
        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());

        Page<SysUser> ret = sysUserRepository.findAllByOrderByCreated(pageRequest);

        //置空密码
        Page<SysUserVO> result = ret.map(k->{
            SysUserVO u = SysUserVO.of(k);
            u.setPassword(null);
            return u;
        });

        return result;
    }


    @Override
    public SysUserVO save(SysUserVO entityVo) {
        //新增用户，需要设置初始密码
        SysUser u = null;
        if (StringUtils.isNotEmpty(entityVo.getId())) {
            u = sysUserRepository.getOne(entityVo.getId());
        }else {
            u = new SysUser();
            u.setValid("Y");
            u.setLimitMultiLogin("N");
        }

        if (u == null) {
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        if (StringUtils.isNotEmpty(entityVo.getLimitedIp()))
            u.setLimitedIp(entityVo.getLimitedIp());

        if (StringUtils.isNotEmpty(entityVo.getLoginName()))
            u.setLoginName(entityVo.getLoginName());

        if (StringUtils.isNotEmpty(entityVo.getUserName()))
            u.setUserName(entityVo.getUserName());

        if (StringUtils.isNotEmpty(entityVo.getPassword())){
            u.setPassword(DigestUtils.md5Hex(entityVo.getPassword()));
            u.setLastChangePwdTime(new Timestamp(System.currentTimeMillis()));
        }
        if (StringUtils.isNotEmpty(entityVo.getValid())) {
            u.setValid(entityVo.getValid());
        }

        u.setUpdateTime(new Date());

        sysUserRepository.save(u);

        SysUserVO ret = SysUserVO.of(u);
        ret.setPassword(null);

        return ret;
    }

    @Override
    public SysUserVO updateUser(SysUserVO sysUserVo) {

        //只允许用户修改这几个选项
        SysUser u = sysUserRepository.getOne(sysUserVo.getId());

        if (StringUtils.isNotEmpty(sysUserVo.getUserName())) {
            u.setUserName(sysUserVo.getUserName());
        }
        if (StringUtils.isNotEmpty(sysUserVo.getLoginName())){
            u.setLoginName(sysUserVo.getLoginName());
        }
        u.setLimitedIp(sysUserVo.getLimitedIp());
        u.setUpdateTime(new Date());

        sysUserRepository.save(u);

        return SysUserVO.of(u);
    }

    /**
     * 重置初始密码
     */
    @Override
    public SysUserVO resetPassword(String userId) {
        SysUser user = sysUserRepository.getOne(userId);
        if (user == null){
            throw  new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }
        user.setPassword(DigestUtils.md5Hex("123456"));
        user.setLastChangePwdTime(new Timestamp(System.currentTimeMillis()));

        sysUserRepository.save(user);

        return SysUserVO.of(user);
    }

    public SysUserVO updatePassword(String userId, String oldPassword, String newPassword){

        SysUser user = sysUserRepository.getOne(userId);

        if (user == null){
            throw  new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        if (user.getPassword().equals(oldPassword)){
            user.setPassword(newPassword);
            user.setLastChangePwdTime(new Timestamp(System.currentTimeMillis()));
        }
        sysUserRepository.save(user);

        return SysUserVO.of(user);
    }

    @Override
    public SysUser findByLoginName(String username) {
        SysUser user = sysUserRepository.findByLoginName(username);

        return user;
    }
}
